<template>
  <section>
    <!--工具条-->
    <div class="gongJv">
      <el-form :inline="true" :model="ruleSelectForm">
        <el-form-item>
          <el-input v-model="ruleSelectForm.trackingNumber" placeholder="物流单号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="ruleSelectForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="ruleSelectForm.orderState" placeholder="订单状态">
            <el-option label="待审核" value="0"></el-option>
            <el-option label="待复审" value="1"></el-option>
            <el-option label="审核未通过" value="2"></el-option>
            <el-option label="待发货" value="3"></el-option>
            <el-option label="已发货" value="4"></el-option>
            <el-option label="交易成功" value="5"></el-option>
            <el-option label="已取消" value="6"></el-option>
            <el-option label="待终审" value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <template>
            <div class="block">
              <el-date-picker
                  v-model="ruleSelectForm.createTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </div>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain  @click="keywordQuery">查询</el-button>
          <el-button type="primary"  plain @click="allChange">导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  plain @click="showMessageBox">导入</el-button>
          <input
              type="file"
              ref="fileInput"
              accept=".xls,.xlsx"
              style="display: none;"
              @change="handleFileChange"
          />
        </el-form-item>
      </el-form>
    </div>
<!--    <el-dialog title="选中需要导出的字段" :visible.sync="isShowExportDiag" width="40%">-->
<!--      <el-row>-->
<!--        <el-col :span="6" style="height: 50px">-->
<!--          <el-checkbox @change="allChange" v-model="allChangeValue">全选</el-checkbox>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--      <el-col :span="6" v-for="(item,index) in columnTitle" :key="index" style="height: 50px">-->
<!--        <el-checkbox v-model="item.checked" @change="changeCheck">{{ item.label }}</el-checkbox>-->
<!--      </el-col>-->
<!--      <span slot="footer" class="dialog-footer" style="display: inline-block;padding-top: 50px">-->
<!--        <el-button @click="isShowExportDiag = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="exportOrder">确 定</el-button>-->
<!--      </span>-->
<!--    </el-dialog>-->
    <el-table :data="acquisitionOrders" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              max-height="550px"  style="width: 100% " >
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="orderSn" label="订单号" width="130" :header-align="'center'" :align="'center'">
        <template slot-scope="scope">
          <span style="color: red;">{{ scope.row.orderSn }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="employee.adminName" label="归属人" width="100" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="customer.customerName" label="客户名" width="100" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="orderAmount" label="订单金额" width="105" sortable :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="payType" label="支付方式" width="110" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="170" sortable :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="orderState" label="订单状态" width="80" :header-align="'center'" :align="'center'">
        <template scope="scope">
          <span v-if="scope.row.orderState == 3" style="color: orange">待发货</span>
          <span v-if="scope.row.orderState == 4" style="color: #50bfff">已发货</span>
          <span v-if="scope.row.orderState == 5" style="color: lightgreen">交易成功</span>
          <span v-if="scope.row.orderState == 6" style="color: lightcoral">订单取消</span>
          <span v-if="scope.row.orderState == 0" style="color: lightcoral">待审核</span>
          <span v-if="scope.row.orderState == 1" style="color: lightcoral">待复审</span>
          <span v-if="scope.row.orderState == 2" style="color: lightcoral">审核未通过</span>
          <span v-if="scope.row.orderState == 7" style="  color: lightcoral">待终审</span>
        </template>
      </el-table-column>
      <el-table-column prop="logisticsMethods" label="物流方式" width="80" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="logisticsCompanies" label="物流公司" width="80" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="trackingNumber" label="物流单号" width="120" :header-align="'center'" :align="'center'">
      </el-table-column>

      <el-table-column prop="lastOperationTime" label="最后操作时间" width="160" sortable :header-align="'center'"
                       :align="'center'">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220" :header-align="'center'"    :align="'center'">
        <template scope="scope">
          <el-button v-perm="'orderList/editOrder'" type="text" size="small"
                     v-if="scope.row.orderState == 3"
                     @click="edit(scope.$index, scope.row)"><i class="el-icon-edit-outline"/>编辑
          </el-button>
          <el-button v-perm="'orderList/send'" type="text" size="small" v-if="scope.row.orderState === 3"
                     @click="sendoutgoods(scope.$index, scope.row)"><i class="el-icon-truck"/>发货
          </el-button>
          <el-button v-perm="'orderProducid/{ordersn}'" type="text" size="small"
                     @click="showData(scope.$index, scope.row)"><i class="el-icon-tickets"/>详情
          </el-button>
          <el-button v-perm="'orderList/cancellation'" type="text" size="small"
                     @click="handleCancel(scope.$index, scope.row)"
                     v-if="scope.row.orderState === 3 || scope.row.orderState === 4 "><i class="el-icon-switch-button"/>取消订单
          </el-button>
          <el-button v-perm="'orderList/collect'" type="text" size="small"
                     v-if=" scope.row.orderState==4"
                     @click="takeDelivery(scope.$index, scope.row)"><i class="el-icon-takeaway-box"/>确认收货
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[5, 10, 20, 50]"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:right; margin-right: 40px;"  >
      </el-pagination>
    </el-col>
    <!-- 发货页面-->
    <el-drawer title="订单发货" :visible.sync="sendoutgoodsFormVisible" :close-on-click-modal="false" size="47%" custom-class="custom-drawer">
      <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane  name="shipment">
            <span slot="label"><i class="el-icon-document"></i>发货信息</span>
            <div class="section">
          <el-form :model="sendoutgoodsForm" label-width="80px" :rules="sendoutgoodsFormRules" ref="sendoutgoodsForm">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="订单编号:">
                  <span>{{ sendoutgoodsForm.orderSn }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单金额:">
                  <span>{{ sendoutgoodsForm.orderAmount }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="下单数量:">
                  <span>{{ sendoutgoodsForm.productNumber }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
            <el-form-item label="物流方式" prop="logisticsMethods">
              <el-select v-model="sendoutgoodsForm.logisticsMethods" placeholder="请选择物流方式" class="custom-input">
                <el-option v-for="item in ShippingMethod" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
              </el-col>
              <el-col :span="12">
            <el-form-item label="快递公司" prop="logisticsCompanies">
              <el-input v-model="sendoutgoodsForm.logisticsCompanies" class="custom-input"></el-input>
            </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="快递单号" prop="trackingNumber">
              <el-input v-model="sendoutgoodsForm.trackingNumber" placeholder="通过导入或者手动输入" class="custom-input"></el-input>
            </el-form-item>
            <el-form-item label="快递备注" prop="remarks">
              <el-input v-model="sendoutgoodsForm.remarks" type="textarea" :rows="3" style="width: 200px" auto-complete="off" class="custom-input"></el-input>
            </el-form-item>
            <el-form-item label="支付方式" prop="paytype">
              <el-input v-model="sendoutgoodsForm.payType" class="custom-input"></el-input>
            </el-form-item>
            <el-form-item label="发货凭证" prop="voucher">
              <el-upload class="upload-demo" name="file" :action="this.$uploadURL" :on-remove="handleFileRemove" :on-success="handleFileUploadsend" :on-exceed="handleFileExceed" :file-list="fileList" :limit=10 :multiple="true" accept=".jpg,.png,.gif" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="支付凭证" prop="receipt">
              <el-upload class="upload-demo" name="file" :action="this.$uploadURL" :on-remove="handleFileRemove" :on-success="handleFileUploadpayment" :on-exceed="handleFileExceed" :file-list="fileList" :limit=10 :multiple="true" accept=".jpg,.png,.gif" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
                <el-button type="primary" @click.native="confirm" :loading="sendoutgoodsLoading">确认</el-button>
                <el-button @click.native="sendoutgoodsFormVisible = false">取消</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane  name="products">
            <span slot="label"><i class="el-icon-collection"></i>产品信息</span>
          <el-form :model="sendoutgoodsForm" label-width="80px" :rules="sendoutgoodsFormRules" ref="sendoutgoodsForm">
            <h3>产品信息</h3>
            <el-table :data="productList" v-loading="listLoading" style="width: 100%;">
              <el-table-column prop="productName" label="产品名称" width="100" :align="'center'"></el-table-column>
              <el-table-column prop="picture" label="产品图片" class="image-container-box" :align="'center'">
                <template slot-scope="scope">
                  <img :src="scope.row.picture" :preview-src-list="[scope.row.picture]" alt="Product Image" style="width: 100px; height: 100px;">
                </template>
              </el-table-column>
              <el-table-column prop="price" label="产品价格" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="costPrice" label="售价" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="orderNum" label="选购数量" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="salePrice" label="成交价" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="orderAmount" label="金额" width="80" :align="'center'"></el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
      </el-tabs>

    </el-drawer>


<!--    订单编辑页面-->
    <el-drawer title="编辑订单" :visible.sync="editFormVisible" :close-on-click-modal="false" size="47%">
     <div class="section">
      <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
       <el-row :gutter="24">
         <el-col :span="12">
        <el-form-item label="订单编号:">
          <span>{{ editForm.orderSn }}</span>
        </el-form-item>
         </el-col>
         <el-col :span="12">
        <el-form-item label="当前状态:">
          <span>{{
              originalOrderState === 3 ? '待发货' : (originalOrderState === 4 ? '已发货' : (originalOrderState === 5 ? '交易成功' : ''))
            }}</span>
        </el-form-item>
         </el-col>
       </el-row>
        <h3>收件信息编辑</h3>
        <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="收件人姓名:" prop="orderDetail.name">
              <el-input v-model="editForm.orderDetail.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人电话:" prop="orderDetail.phone">
              <el-input v-model="editForm.orderDetail.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="36">
          <el-col :span="12">
            <el-form-item label="所属省份:" prop="province">
              <el-input v-model="editForm.orderDetail.province"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属市:" prop="city">
              <el-input v-model="editForm.orderDetail.city"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区:" prop="district">
              <el-input v-model="editForm.orderDetail.district"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址:" prop="detailAddress">
          <el-input v-model="editForm.orderDetail.detailAddress" type="textarea" :rows="2"
                    style="width: 500px"></el-input>
        </el-form-item>

        <el-form-item label="支付方式" prop="payType">
          <el-input v-model="editForm.payType">
          </el-input>
        </el-form-item>
        <el-form-item label="订单备注" prop="payType">
          <el-input v-model="editForm.notes" type="textarea" :rows="2">
          </el-input>
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-radio-group v-model="editForm.paymentStatus">
            <el-radio :label="textToValueMapping.paymentStatus['已支付']">已支付</el-radio>
            <el-radio :label="textToValueMapping.paymentStatus['欠款']">欠款</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="editdata" :loading="editLoading">确认</el-button>
        <el-button @click.native="editFormVisible = false">取消</el-button>

      </div>
     </div>
    </el-drawer>

    <!--  取消订单-->
    <el-dialog title="取消订单" :visible.sync="cancellationFormVisible" :close-on-click-modal="false">
      <el-form :model="cancellationForm" label-width="100px" ref="cancellationForm" :rules="cancellationFormRules">
        <h3> 订单信息</h3>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="订单编号:">
              <span>{{ cancellationForm.orderSn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单备注:">
              <span>{{ cancellationForm.notes }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态:">
              <span>{{ getOrderStateText(cancellationForm.orderState) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="取消原因:" prop="reasonForCancellation">
          <el-input v-model="cancellationForm.reasonForCancellation" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancellationFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="ConfirmCancel" :loading="cancellationFormLoding">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="取消原因" :visible.sync="cancelFormVisible" :close-on-click-modal="false">
      <el-form :model="cancellationForm" label-width="80px" ref="cancellationForm">
        <el-form-item label="取消原因:" prop="reasonForCancellation">
          <span>{{ cancellationForm.reasonForCancellation }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancelFormVisible = false">我已了解</el-button>
      </div>
    </el-dialog>

    <!--    订单详情-->
    <el-drawer title="订单详情" :visible.sync="acquisitionOrderShowFormVisible" :close-on-click-modal="false" size="49%">
      <el-steps finish-status="success" :active="currentStep" space="300px" align-center v-if="[3, 4, 5].includes(currentStep)">
        <el-step title="待发货" :status="getStepStatus(0)" :description="acquisitionOrderShowFrom.createTime">
          <template v-slot:icon>
            <i v-if="getStepStatus(0) === 'wait'" class="el-icon-loading"></i>
          </template>
        </el-step>
        <el-step title="已发货" :status="getStepStatus(1)" :description="acquisitionOrderShowFrom.deliveryTime">
          <template v-slot:icon>
            <i v-if="getStepStatus(1) === 'wait'" class="el-icon-loading"></i>
          </template>
        </el-step>
        <el-step title="交易完成" :status="getStepStatus(2)" :description="acquisitionOrderShowFrom.successTime">
          <template v-slot:icon>
            <i v-if="getStepStatus(2) === 'wait'" class="el-icon-loading"></i>
          </template>
        </el-step>
      </el-steps>
      <el-tabs v-model="showorderTab" type="border-card">
        <el-tab-pane name="orderbasic">
          <span slot="label"><i class="el-icon-tickets"></i>基本信息</span>
          <div class="section">
          <el-form :model="acquisitionOrderShowFrom" label-width="100px" ref="acquisitionOrderShowFrom">
            <h3>一 基本信息</h3>
            <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="订单编号:">
                  <span>{{ acquisitionOrderShowFrom.orderSn }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="客户姓名:">
                  <span>{{ acquisitionOrderShowFrom.customer.customerName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户电话:">
                  <span>{{ acquisitionOrderShowFrom.customer.phoneNumber }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单状态:">
                  <span>{{ getOrderStateText(acquisitionOrderShowFrom.orderState) }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="客户销售渠道:">
                  <div>{{ gettypeNameById(acquisitionOrderShowFrom.customer.typeId) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户级别:">
                  <div>{{ getlabelNameById(acquisitionOrderShowFrom.customer.labelId) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户来源:">
                  <div>{{ getsourceNameById(acquisitionOrderShowFrom.customer.sourceId) }}</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
            <el-col :span="24">
            <el-form-item label="订单备注:">
              <span>{{ acquisitionOrderShowFrom.notes }}</span>
            </el-form-item>
          </el-col>
            </el-row>
            <h3>二 收货人信息</h3>
            <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="收件人姓名:">
                  <span>{{ acquisitionOrderShowFrom.orderDetail.name }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收件人电话:">
                  <span>{{ acquisitionOrderShowFrom.orderDetail.phone }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="所属省份:">
                  <span>{{ acquisitionOrderShowFrom.orderDetail.province }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属市:">
                  <span>{{ acquisitionOrderShowFrom.orderDetail.city }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属区:">
                  <span>{{ acquisitionOrderShowFrom.orderDetail.district }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="详细地址:">
              <span>{{ acquisitionOrderShowFrom.orderDetail.detailAddress }}</span>
            </el-form-item>
          </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane name="logistics">
          <span slot="label"><i class="el-icon-truck"></i>物流信息</span>
          <div class="section">
          <el-form :model="acquisitionOrderShowFrom" label-width="100px" ref="acquisitionOrderShowFrom">
            <h3>三 物流信息</h3>
            <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="发货方式:">
                  <span>{{ acquisitionOrderShowFrom.logisticsMethods }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="快递公司:">
                  <span>{{ acquisitionOrderShowFrom.logisticsCompanies }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="快递单号:">
                  <div>{{ acquisitionOrderShowFrom.trackingNumbe }}</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="下单数量:">
              <div>{{ acquisitionOrderShowFrom.productNumber }}箱</div>
            </el-form-item>
            <el-form-item label="物流备注:">
              <div>{{ acquisitionOrderShowFrom.remarks }}</div>
            </el-form-item>
            <el-form-item label="发货凭证:">
              <el-image class="image-container" v-for="(url, index) in acquisitionOrderShowFrom.voucher"
                        :key="index" :src="url"
                        fit="contain" :preview-src-list="acquisitionOrderShowFrom.voucher"
                        style="max-width: 100%; max-height: 100%;">
              </el-image>
            </el-form-item>
            <h3>四 回款信息</h3>
            <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">
            <el-form-item label="订单金额:">
              <div>{{ acquisitionOrderShowFrom.orderAmount }}</div>
            </el-form-item>
            <el-form-item label="支付凭证:">
              <el-image class="image-container" v-for="(url, index) in acquisitionOrderShowFrom.receipt"
                        :key="index" :src="url"
                        fit="contain" :preview-src-list="acquisitionOrderShowFrom.receipt"
                        style="width: 100px; height: 100px;">
              </el-image>
            </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane name="product">
          <span slot="label"><i class="el-icon-collection"></i>产品信息</span>
          <div class="section">
            <el-table :data="productList" v-loading="listLoading" style="width: 100%;">
              <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>
              <el-table-column prop="picture" class="image-container-box" width="130" label="产品图片">
                <template slot-scope="scope">
                  <img :src="scope.row.picture" :preview-src-list="[scope.row.picture]" alt="Product Image"
                       class="image-container">
                </template>
              </el-table-column>
              <el-table-column prop="price" label="产品价格" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="costPrice" label="售价" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="orderNum" label="选购数量" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="salePrice" label="成交价" width="80" :align="'center'"></el-table-column>
              <el-table-column prop="orderAmount" label="金额" width="80" :align="'center'"></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

  </section>
</template>

<script>

export default {
  computed: {
    currentStep() {
      return this.acquisitionOrderShowFrom.orderState;
    }
  },
  data() {
    return {
      activeTab:'shipment',
      showorderTab:'orderbasic',
      originalOrderState: '',
      ruleSelectForm: {
        phone: '',
        trackingNumber: '',
        orderState: '',
        createTime: [],
      },
      total: 0,

      activeName: 'order',
      fileList: [],
      //数据转换
      textToValueMapping: {
        orderState: {
          '待发货': 3,
          '已发货': 4,
          '交易成功': 5,
        },
        paymentStatus: {
          '已支付': 1,
          '欠款': 2,
        },
      },
      //分页显示所属数据
      acquisitionOrders: [],//所有订单


      listLoading: false,
      listLoadingproduct: false,
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5, 10, 20, 50], // 可选择的每页条数
      totals: 0,
      dersdeliverytotals: 0,
      Shippedtotals: 0,
      markettotals: 0,
      Canceledtotals: 0,

      //高级查询所需数据

      keyword: '',

      //多条数据选中
      sels: [],//列表选中列
      employee: [],
      //订单编辑
      editFormVisible: false,
      editForm: {
        orderSn: '',
        orderState: '',
        paymentStatus: '',
        paytype: '',
        receipt: '',
        orderDetail: {},
      },
      editFormRules: {
        'orderDetail.name': [{
          required: true, message: '收件人姓名不能为空', trigger: 'blur'
        }],
        'orderDetail.phone': [{
          required: true, message: '收件电话不能为空', trigger: 'blur'
        }],
        address: [{
          required: true, message: '请输入详细地址', trigger: 'blur'
        }],

      },
      editLoading: false,
      //发货
      ShippingMethod: [
        {label:"快递",value:"快递"},{label:"物流",value:"物流"},{label:"自提",value:"自提"},
        {label:"自己叫车",value:"自己叫车"},{label:"整车拉",value:"整车拉"},
      ],
      sendoutgoodsLoading: false,
      sendoutgoodsFormVisible: false,
      sendoutgoodsForm: {
        trackingNumber: '',
        orderSn: '',
        logisticsMethods: '',
        logisticsCompanies: '',
        notes: '',
        voucher: [],//发货凭证
        receipt: [],//收款凭证，支付凭证
        remarks:'',//快递备注
      },
      sendoutgoodsFormRules: {
        logisticsMethods: [{
          required: true, message: '请选择发货方式', trigger: 'blur'
        }],

        logisticsCompanies: [{
          required: true, message: '请选择物流公司', trigger: 'blur'
        }],
        trackingNumbe: [{
          required: true, message: '请输入快递单号', trigger: 'blur'
        }],
        /* voucher:[{
           required: true, message: '请上传发货凭证', trigger: 'blur'
         }],*/
      },
//取消订单
      cancellationFormVisible: false,
      cancellationFormLoding: false,
      cancellationForm: {
        orderSn: '',
        notes: '',
        orderState: '',
        reasonForCancellation: '',
      },
      cancellationFormRules: {

        reasonForCancellation: [{
          required: true, message: '请输入取消原因', trigger: 'blur'
        }],
      },

      //取消订单原因
      cancelFormVisible: false,
      //取消的数据详情
      cancelOrderShowFormVisible: false,
      cancelOrderShowFrom: {
        orderAmount: '',
        customer: {},
        productId: '',
        customerId: '',
        typeId: '',
        orderSn: '',
        orderState: '',
        labelId: '',
        sourceId: '',
        logisticsMethods: '',
        logisticsCompanies: '',
        trackingNumbe: '',
        notes: '',
        createTime: '',
        deliveryTime: '',
        successTime: '',
        receipt: '',
        productNumber: '',
      },

      //确认订单
      acquisitionOrderFormVisible: false,
      acquisitionOrderLoading: false,
      acquisitionOrderFormRules: {},
      acquisitionOrderForm: {
        id: null,
        paytype: '',
        price: ''
      },
      //显示详情
      acquisitionOrderShowFormVisible: false,
      acquisitionOrderShowLoading: false,
      acquisitionOrderShowFrom: {
        orderDetail: {},
        productNumber: '',
        orderAmount: '',
        customer: {},
        productId: '',
        customerId: '',
        typeId: '',
        orderSn: '',
        orderState: '',
        labelId: '',
        sourceId: '',
        logisticsMethods: '',
        logisticsCompanies: '',
        trackingNumbe: '',
        notes: '',
        createTime: '',
        deliveryTime: '',
        successTime: '',
        receipt: [],
      },
      // 客户销售渠道
      custoLabel: [],
      // 客户销售渠道
      custoType: [],
      //客户来源
      custoSource: [],
      serousList: [],
      productList: {},
      isShowExportDiag: false,
      columnTitle: [
        {label: '订单号', checked: false, prop: 'orderId'},
        {label: '归属人', checked: false, prop: 'userName'},
        {label: '客户名', checked: false, prop: 'customName'},
        {label: '订单金额', checked: false, prop: 'amount'},
        {label: '支付方式', checked: false, prop: 'payType'},
        {label: '下单时间', checked: false, prop: 'createTime'},
        {label: '物流方式', checked: false, prop: 'logisticsMethods'},
        {label: '物流公司', checked: false, prop: 'logisticsCompanies'},
        {label: '物流单号', checked: false, prop: 'trackingNumber'},
        {label: '订单状态', checked: false, prop: 'orderStatus'},
        {label: '最后操作时间', checked: false, prop: 'lastOperationTime'},
      ],
      allChangeValue: false,
      //全局选择的订单编号
      globalSelected:[],

    }
  },
  methods: {
    // changeCheck(flag) {
    //   if (!flag) {
    //     this.allChangeValue = false;
    //   } else {
    //     let isAll = true;
    //     for (let i = 0; i < this.columnTitle.length; i++) {
    //       if (!this.columnTitle[i].checked) {
    //         isAll = false;
    //         return;
    //       }
    //     }
    //     if (isAll) {
    //       this.allChangeValue = true;
    //     }
    //   }
    // },
    // 显示加载状态

    allChange(flag) {
      if (flag) {
        this.columnTitle.forEach((item) => {
          item.checked = true;
        })
        this.exportOrder();
      } else {
        this.columnTitle.forEach((item) => {
          item.checked = false;
        })
      }
    },
    async exportOrder() {
      let orderSn = this.globalSelected.map(item => item.orderSn);
      if (!orderSn.length) {
        this.$notify.error({
          title: '警告',
          message: '请至少选择一个订单进行导出'
        });
      } else {
        const loadingNotification = this.$notify({
          title: '信息',
          message: '订单导出处理中，请稍候...',
          type: 'info',
          duration:0,
          showClose:false,
        });
        const exportOrderDto = {orderSn: orderSn};
        try {
          // 使用全局配置的 axios 发送请求
          const response = await this.$http.post('/orderList/export', exportOrderDto, {
            responseType: 'blob' // 设置响应类型为 blob
          });
          // 获取响应的 Blob 数据
          const url = window.URL.createObjectURL(new Blob([response.data]));
          loadingNotification.close();
          // 创建下载链接并下载文件
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', '订单信息表.xls');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 清空全局选中项并重新加载订单
          this.globalSelected = [];
          this.getAcquisitionOrders();
        } catch (error) {
          console.error('导出订单失败:', error);
          this.$notify.error({
            title: '导出失败',
            message: '导出订单失败，请稍后重试。'
          });
        }
      }
    },
    // 显示MessageBox提示
    showMessageBox() {
      this.$confirm(
          `
        <div >
          <p style="font-weight: bold;">请确保您选择的文件格式为 .xls 或 .xlsx。如果文件格式或内容不正确，可能会导致上传失败。需要注意以下数据格式：</p>
          <ul style="list-style-type: disc; margin-left: 10px;">
            <li><strong>订单编号不能为空，禁止修改！</strong></li>
            <li><strong>订单状态必须为 "待发货"，否则会跳过该条数据！</strong></li>
            <li><strong>物流单号应为有效数据，并且不能为空！</strong></li>
            <li><strong>文件内禁止有合并单元格数据，列名信息除外！</strong></li>
          </ul>
          <p style="font-weight: bold;">如果弹出错误提示，请根据错误信息对文件数据进行修改，再次上传导入！</p>
        </div>
        `,
          '文件上传提示',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            customClass: 'messageboxclass'
          }
      ).then(() => {
        this.openFileUpload();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导入'
        });
      });
    },
    // 打开文件上传对话框
    openFileUpload() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择逻辑
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.importOrder(file);
      }
    },

    //导入
    importOrder(file) {
      // 判断文件类型
      const fileType = file.type;
      if (fileType !== 'application/vnd.ms-excel' && fileType !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$notify.error({
          title: '警告',
          message: '只能上传Excel文件'
        });
        return false;
      }

      // 创建FormData对象
      const formData = new FormData();
      formData.append("file", file);
      const orderImport = this.$notify({
        title: '导入提示',
        message: '订单导入处理中，请稍候...',
        type: 'info',
        duration:0,
        showClose:false,
      });
      // 发送POST请求
      this.$http.post('/orderList/importOrder/', formData)
          .then(response => {
            if (response && response.data) {
              const result = response.data;

              if (result.success) {
                orderImport.close();
                this.$notify.success({
                  title: '导入提示',
                  message: '数据导入成功',
                });

                this.getAcquisitionOrders();
              } else {
                orderImport.close();
                if (result.resultObj && result.resultObj.length > 0) {
                  let errorMessages = '部分数据导入失败<br>';
                  result.resultObj.forEach(error => {
                    errorMessages += `订单编号: <span style="color:#2d8cf0;">${error.orderSn}</span>, 错误信息:<span style="color:#e64242;"> ${error.errorMessage}</span><br>`;
                  });
                  errorMessages += '<br>请根据上述错误信息进行修改后再次提交。';
                  this.$notify.error({
                    title: '导入错误',
                    dangerouslyUseHTMLString: true,
                    message: errorMessages,
                    duration: 0
                  });

                } else {
                  orderImport.close();
                  this.$notify.error({
                    title: '导入错误',
                    message: '未预期的错误信息格式'
                  });

                }
              }
            } else {
              orderImport.close();
              this.$notify.error({
                title: '导入错误',
                message: '未预期的响应格式'
              });

            }
          })
          .catch(error => {
            orderImport.close();
            this.$notify.error({
              title: '导入错误',
              message: `上传失败：${error.message}`
            });
          }).finally(() => {
        // 重置文件输入元素
        this.$refs.fileInput.value = '';
      });
    },
    getStepStatus(step) {
      const orderState = this.acquisitionOrderShowFrom.orderState;

      if (orderState - 3 == step) {
        return "success"; // 当前步骤已完成
      } else if (orderState - 3 > step) {
        return "success"; // 当前步骤进行中
      } else {
        return "wait"; // 当前步骤待进行
      }
    },
    //是否显示核销订单按钮
    shouldShowWriteOffButton(row) {
      return row.findingOfAudit !== 1;
    },
    //数据转换
    getOrderStateText(orderState) {
      if (orderState === 3) {
        return '待发货';
      } else if (orderState === 4) {
        return '已发货';
      } else if (orderState === 5) {
        return '交易成功';
      } else if (orderState === 6) {
        return '订单已取消';
      }else if (orderState === 1) {
        return '待复审';
      }else if (orderState === 2) {
        return '审核未通过';
      }else if (orderState === 0) {
        return '待审核';
      }else if (orderState === 7) {
        return '待终审';
      } else {
        return '未知状态';
      }
    },
    //获取客户信息
    gettypeNameById(typeId) {
      const category = this.custoType.find(item => item.id === typeId);
      return category ? category.customerType : '';
    },
    getlabelNameById(labelId) {
      const category = this.custoLabel.find(item => item.id === labelId);
      return category ? category.customerLabel : '';
    },
    getsourceNameById(sourceId) {
      const category = this.custoSource.find(item => item.id === sourceId);
      return category ? category.customerSource : '';
    },
    //获取类型
    getType() {
      this.$http.get("/customerType").then(res => {
        this.custoType = res.data;
      })
    },
    //获取标签
    getLabel() {
      this.$http.get("/customerLabel").then(res => {
        this.custoLabel = res.data;
      })
    },
    //获取来源
    getSerouce() {
      this.$http.get("/customerSource").then(res => {
        this.custoSource = res.data;
      })
    },
//获取产品数据
    getproductLists: function (productId) {
      this.$http.get(`/productList/list/${productId}`).then((res) => {
        // 使用 Object.values 将对象转换为数组
        this.productList = res.data;
      });
    },

    keywordQuery() {
      //查询完，原来分页条件已经没用了，要跑到第一页去
      this.currentPage = 1;
      this.getAcquisitionOrders();
    },

    //获取订单列表
    getAcquisitionOrders() {
      // 将开始时间和结束时间转换为字符串
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ruleSelectForm: {
          ...this.ruleSelectForm,
          startTime: this.ruleSelectForm.createTime ? this.ruleSelectForm.createTime[0] : null,
          endTime: this.ruleSelectForm.createTime ? this.ruleSelectForm.createTime[1] : null
        }
      };
      this.listLoading = true;
      this.$http.post("/orderList", para).then(res => {
        this.totals = res.data.total;
        this.acquisitionOrders = res.data.records.map(order => ({
          ...order,
          receipt: order.receipt ? order.receipt.split(',') : [],
          voucher: order.voucher ? order.voucher.split(',') : []
        }));
        this.currentPage = para.currentPage; // 更新当前页数
        this.listLoading = false;
      }).catch(result => {
        this.$message.error("系统繁忙，请稍后重试!!!")
      })
    },

    //显示发货页面
    sendoutgoods: function (index, row) {
      this.sendoutgoodsFormVisible = true;
      this.sendoutgoodsForm = Object.assign({}, row);
      const orderSn = this.sendoutgoodsForm.orderSn;
      //根据订单编号查询订单中间表获取产品信息
      this.$http.post("/orderProducid/" + orderSn).then(res => {
        // 使用 Object.values 将对象转换为数组
        this.productList = res.data;
      });
    },

    //订单编辑页面
    edit: function (index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
      this.originalOrderState = row.orderState;
    },
    //显示取消订单页面
    handleCancel: function (index, row) {
      this.cancellationForm = Object.assign({}, row);
      this.cancellationFormVisible = true;
    },
    // 取消订单详情
    cancelshowData: function (index, row) {
      this.cancelOrderShowFrom = Object.assign({}, row);
      this.cancelOrderShowFormVisible = true;
    },
    //显示详情界面
    showData: function (index, row) {
      this.acquisitionOrderShowFrom = Object.assign({}, row);
      this.acquisitionOrderShowFormVisible = true;
      this.getType();
      this.getLabel();
      this.getSerouce();
      const orderSn = this.acquisitionOrderShowFrom.orderSn;
      //根据订单编号查询订单中间表获取产品信息
      this.$http.post("/orderProducid/" + orderSn).then(res => {
        // 使用 Object.values 将对象转换为数组
        this.productList = res.data;
      });
    },


    //确认收货
    takeDelivery:function (index,row){
      const ordersn =row.orderSn;
      this.$confirm('确认'+ordersn+'订单收货吗','温馨提示',{}).then(()=>{
        this.$http.put("orderList/takeDelivery/"+ ordersn).then(res=>{
          if (res.data.success) {
            this.$message({
              message: '收货成功',
              type: 'success'
            });
          }
        })
        this.getAcquisitionOrders();
      })
    },


    //保存
    confirmOrder: function () {
      this.$refs.acquisitionOrderForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认订单吗？', '温馨提示', {}).then(() => {
            this.acquisitionOrderLoading = true;
            //拷贝一份新数据
            let para = Object.assign({}, this.acquisitionOrderForm);
            this.$http.post("/orderPetAcquisition/confirm", para).then(res => {
              //去除忙等框
              this.acquisitionOrderLoading = false;
              //做提示
              if (res.data.success) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
              //关闭对话框
              this.acquisitionOrderFormVisible = false;
              //重新查询数据
              this.getAcquisitionOrders();
            }).catch(result => {
              alert("系统错误！");
              this.acquisitionOrderLoading = false;
            });
          });
        }
      });
    },
    //提交编辑
    editdata: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交编辑吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            para.voucher = para.voucher.join(',');
            para.receipt = para.receipt.join(',');
            this.$http.put("/orderList/editOrder", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              //更新当前页面数据
              this.getAcquisitionOrders();
            });
          });
        }
      });
    },
    //发货确认
    confirm: function () {
      this.$refs.sendoutgoodsForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认发货吗？', '提示', {}).then(() => {
            this.sendoutgoodsLoading = true;
            let para = Object.assign({}, this.sendoutgoodsForm);
            para.voucher = para.voucher.join(',');
            para.receipt = para.receipt.join(',');
            this.$http.put("/orderList/sendoutgoods", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['sendoutgoodsForm'].resetFields();
                this.sendoutgoodsForm = {};
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.sendoutgoodsLoading = false;
              this.sendoutgoodsFormVisible = false;
              //更新发货页面数据
              this.getAcquisitionOrders();
            });
          });
        }
      });
    },

    //所有选中对象都会传进来
    selsChange(sels) {
      this.sels = sels;
      // 更新全局选中数据
      this.globalSelected = this.globalSelected.filter(
          item => !this.acquisitionOrders.some(order => order.orderSn === item.orderSn)
      );
      this.globalSelected = this.globalSelected.concat(this.sels);
    },
    //2.点击分页实现
    handleCurrentChange(currentPage) {
      this.saveCurrentSelection();
      this.currentPage = currentPage;
      this.getAcquisitionOrders();
    },
    handleSizeChange(val) {
      this.saveCurrentSelection();
      this.pageSize = val;
      this.currentPage = 1; // 重置当前页码为1
      this.getAcquisitionOrders();
    },
    saveCurrentSelection() {
      // 将当前页的选中状态保存到全局选中状态中
      this.sels.forEach(item => {
        if (!this.globalSelected.some(selected => selected.orderSn === item.orderSn)) {
          this.globalSelected.push(item);
        }
      });
    },
    updateSelection() {
      // 在每次分页加载时，更新当前页的选中状态
      this.$nextTick(() => {
        const table = this.$refs.table;
        if (table) {

          const selectedOrderSns = this.globalSelected.map(item => item.orderSn);
          this.acquisitionOrders.forEach(item => {
            if (selectedOrderSns.includes(item.orderSn)) {
              table.toggleRowSelection(item, true);
            }
          });
        }
      });
    },
//文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.picture = response.resultObj;
      }
    },
    //文件上传成功之后的修改页面回调
    handleFileUploadedit(response) {
      if (response.success) {
        this.editForm.receipt = response.resultObj;
      }
    },
    //发货凭证上传成功后
    handleFileUploadsend(response) {
      if (response.success) {
        this.sendoutgoodsForm.voucher.push(response.resultObj);
      }
    },
    //支付凭证上传成功后
    handleFileUploadpayment(response) {
      if (response.success) {
        this.sendoutgoodsForm.receipt.push(response.resultObj);
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },

    //取消订单
    ConfirmCancel: function (index, row) {
      this.$refs.cancellationForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认取消该订单吗？', '提示', {}).then(() => {
            this.cancellationFormLoding = true;
            let para = Object.assign({}, this.cancellationForm);
            para.voucher = para.voucher.join(',');
            para.receipt = para.receipt.join(',');
            this.$http.put("/orderList/cancel", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['cancellationForm'].resetFields();
                this.cancellationForm = {};
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.cancellationFormLoding = false;
              this.cancellationFormVisible = false;
              //更新页面数据
              this.getAcquisitionOrders();
              // 更新下页面
            });
          });
        }
      });
    },
  },

  mounted() {
    this.getAcquisitionOrders();
  }
}

</script>
<style>
.messageboxclass{
  width: 500px;
}
</style>
<style scoped>
.marked-status {
  position: relative;
  display: inline-block;
  color: pink; /* 字体颜色为粉红色 */
}

.gongJv {
  margin-top: 20px;
}

.marked-status::before {
  content: "";
  position: absolute;
  top: 50%;
  left: -15px; /* 负值，使得方框向左偏移，可以根据实际需求调整 */
  width: 10px; /* 方框宽度 */
  height: 100%; /* 方框高度与文本一致 */
  background-color: lightcoral; /* 背景颜色为浅红色 */
}
.section {
  margin-bottom: 5px;
  padding: 30px;
  background: #f9f9f9;
  border-radius: 4px;
}
</style>